package kr.saeildamil.androidstudty.ch19;

import kr.saeildamil.androidstudty.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class AsyncTaskBasic extends Activity {
	TextView tv;
	int mValue;
	ProgressDialog mProgress;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_longtime);
		
		tv=(TextView) findViewById(R.id.ch19_longtime_count);
	}
	public void mOnClick(View v){
		new AccumulateTask().execute(100);
	}
	
	class AccumulateTask extends AsyncTask<Integer, Integer, Integer>{
		@Override
		protected void onPreExecute() {
			Log.d("AsyncTask", "onPreExecute()");
			mValue=0;
			mProgress=new ProgressDialog(AsyncTaskBasic.this);
			mProgress.setProgress(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle("Updating");
			mProgress.setMessage("Waiting...");
			mProgress.setCancelable(false);
			mProgress.setProgress(0);
			mProgress.setButton("Cancle",new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					cancel(true);
				}
			});
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(Integer... params) {
			Log.d("AsyncTask", "doInBackground()"+params[0]);
			while (!isCancelled()) {
				mValue++;
				if(mValue<=100){
					publishProgress(mValue);
				}else
					break;
			}
			try {
				Thread.sleep(50);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return mValue;
		}
		@Override
		protected void onProgressUpdate(Integer... values) {
			Log.d("AsyncTask", "onProgressUpdate()"+values[0]);
			super.onProgressUpdate(values);
			mProgress.setProgress(values[0]);
		}
		@Override
		protected void onPostExecute(Integer result) {
			Log.d("AsyncTask", "onPostExecute()"+result);
			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

	}
}
